<template>
	<div class="system-dic-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search mb15">
				<el-upload ref="upload" class="ml10"
                   :action='httpFileUrl'
                   :limit="1"
                   :headers="httpFileHeaders"
					         :on-exceed="handleExceed"
                   :on-success="onSuccess"
                   :auto-upload="false"
        >

					<template #trigger>
						<el-button type="primary">上传附件</el-button>
					</template>
					<el-button class="ml-10" type="success" @click="submitUpload">
						提交
					</el-button>
					<template #tip>
						<div class="el-upload__tip text-red ">
							{{ $t('message.router.ossinfo') }}
						</div>
					</template>

				</el-upload>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
				<el-table-column type="index" label="序号" width="80">
					<template #default="scope">
						{{ scope.$index + 1 }}
					</template>
				</el-table-column>
				<el-table-column prop="ossId" label="ID" show-overflow-tooltip></el-table-column>
				<el-table-column prop="originalName" label="原名称" width="200" show-overflow-tooltip></el-table-column>

				<el-table-column prop="url" label="网络地址" width="600" show-overflow-tooltip>
					<template #default="scope">
						<p ref="copyTextRef" >{{ scope.row.url }}</p>
					</template>
				</el-table-column>
				<el-table-column prop="createdTime" label="创建时间" show-overflow-tooltip></el-table-column>
				<el-table-column prop="fileSuffix" label="后缀" show-overflow-tooltip>
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.status == 0">启用</el-tag>
						<el-tag type="info" v-else>禁用</el-tag>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="150">
					<template #default="scope">
						<el-button size="small" text type="primary"
							@click="handlePreview(scope.row.ossId)">预览</el-button>
						<el-button size="small" text type="primary" @click="copy(scope.row.url)" >复制</el-button>
						<el-button size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
				:pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.tableData.param.pageNum" background
				v-model:page-size="state.tableData.param.pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total">
			</el-pagination>
		</el-card>
		<el-image-viewer v-if="showImagePreview" :zoom-rate="1.2" @close="closePreview" :url-list="imgPreviewList" />
		<DicDialog ref="dicDialogRef" @refresh="formSubmit" />
	</div>
</template>

<script setup lang="ts" name="systemDic">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, genFileId } from 'element-plus';
import { ossApi } from '/src/api/system/oss';
import { isEmpty, tansParams } from '/src/utils/mms';
import { Session } from '/src/utils/storage';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
import useClipboard from 'vue-clipboard3';
const { toClipboard } = useClipboard()
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
// 引入组件
const DicDialog = defineAsyncComponent(() => import('/src/views/system/dict/dialog.vue'));
// 引入 api 请求接口
const baseApi = ossApi();
const upload = ref<UploadInstance>()

const dicDialogRef = ref();
const state = reactive<SysOssState>({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			name: '',
			pageNum: 1,
			pageSize: 10,
		},
	},
});

// 图片预览
const imgPreviewList = ref<any>([])
const showImagePreview = ref(false)


// 复制文本    npm install --save vue-clipboard3
// const { toClipboard } = useClipboard()
const copy=(txt:string)=>{
	toClipboard(txt).then(()=>{
		ElMessage.success("复制成功！");
	}).catch(()=>{
		ElMessage.warning("复制失败！");
	})
}
// 图片上传
const httpFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/system/oss');
const httpFileHeaders = ref({
	'Authorization': `${Session.get('token')}`
});
// 当超出限制时
const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles()
	const file = files[0] as UploadRawFile
	file.uid = genFileId()
	upload.value!.handleStart(file)
}
//上传成功
const onSuccess: UploadProps['onSuccess'] = (files) => {
	upload.value!.clearFiles()
	getTableData();
}
// 提交上传
const submitUpload = () => {
	upload.value!.submit()
}

// 图片预览
const handlePreview = async (ossId: string) => {
	const base64Image = await baseApi.query(ossId).then(res=>{
		console.log(res.data.base64);
		showImagePreview.value=true;
	    imgPreviewList.value=['data:image/png;base64,'+res.data.base64];
	})
}
// 关闭预览
const closePreview = () => {
	imgPreviewList.value = []
	showImagePreview.value = false
}

// 接受子组件传值
const formSubmit = (row: RowDicType) => {

	if (isEmpty(row.id)) {
		//新增
		baseApi.insert(row).then(row => {
			dicDialogRef.value.closeDialog();
			ElMessage.success(row.msg)
			setTimeout(() => {
				getTableData();
			}, 1000)
		}).catch(async err => { ElMessage.warning(err); }).finally(() => { })
	} else {
		//更新
		baseApi.edit(row).then(row => {
			dicDialogRef.value.closeDialog();
			ElMessage.success(row.msg)
			setTimeout(() => {
				getTableData();
			}, 1000)
		}).catch(async err => { ElMessage.warning(err); }).finally(() => { })
	}

}
// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	const data = [];
	baseApi.list(state.tableData.param).then(res => {
		state.tableData.data = res.rows;
		state.tableData.total = res.total;
		state.tableData.loading = false;
	}).catch(async err => { ElMessage.warning(err); }).finally(() => { })
};
// 打开新增字典弹窗
const onOpenAddDic = (type: string) => {
	dicDialogRef.value.openDialog(type);
};
// 打开修改字典弹窗
const onOpenEditDic = (type: string, row: RowOssType) => {
	baseApi.query(row.ossId).then(res => {
		dicDialogRef.value.openDialog(type, res.data);
	}).catch(async err => { ElMessage.warning(err); }).finally(() => { })
};
// 删除字典
const onRowDel = (row: RowOssType) => {
	ElMessageBox.confirm(`此操作将永久删除文件名称：“${row.originalName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			baseApi.delete(row.ossId).then(res => {
				getTableData();
				ElMessage.success('删除成功');
			}).catch(async err => { ElMessage.warning(err); }).finally(() => { })
		})
		.catch(() => { });
};
// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getTableData();
};
// 页面加载时
onMounted(() => {
	getTableData();
});
</script>
<style scoped lang="scss">
.ml-10 {
	margin-left: 10px;
}
</style>
